package com.lx.zy.project.system.controller;


import com.lx.zy.common.constant.Constants;
import com.lx.zy.common.utils.ServletUtils;
import com.lx.zy.framework.security.LoginUser;
import com.lx.zy.framework.security.service.SysLoginService;
import com.lx.zy.framework.security.service.SysPermissionService;
import com.lx.zy.framework.security.service.TokenService;
import com.lx.zy.framework.web.domain.AjaxResult;
import com.lx.zy.project.system.domain.SysMenu;
import com.lx.zy.project.system.domain.SysUser;
import com.lx.zy.project.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * @program: zy-vue
 * @description: 后台系统登录
 * @author: Lx
 * @create: 2019-10-16 00:43
 **/
@RestController
public class SysLoginController
{
    // public static final Logger logger = LogUtil.getLogger(SysLoginService.class);
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysMenuService menuService;

    @PostMapping("/login")
    public AjaxResult login(String username, String password, String code, String uuid)
    {

        //  logger.debug("请求了/login");
        AjaxResult ajaxResult = AjaxResult.success();
        //生成令牌
        String token = loginService.login(username, password, code, uuid);
        ajaxResult.put(Constants.TOKEN, token);
        return ajaxResult;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        //角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        //权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
